var BaseConst = require('./Const'),
	BaseFun = require('./Function'),
	http = require("http"),
	socketIo = require('socket.io')(http);

//发送给指定连接
exports.emitBySocketId = function(socketId, eventName, data){
	if(clientList.hasOwnProperty(socketId)){
		clientList[socketId].emit(eventName, data);
	}
}

//广播给所有人
exports.emit = function(eventName, data){
	socketIo.emit(eventName, data);
};
//广播给该房间的所有人
exports.emitRoom = function(eventName, roomName, data){
	socketIo.in(roomName).emit(eventName, data);			//广播给所有人，包括自己
};

var clientList = {};
var createServer = function(socketPort){
	var server = http.createServer().listen(socketPort);
	socketIo.listen(server);

	socketIo.on('connection', function(socket) {
		// socketIo.emit('login', {msg: '欢迎'});

		if(!clientList.hasOwnProperty(socket.id)){
			clientList[socket.id] = socket;
		}

		socket.on('toSelf', function(data) {
			socket.emit(data.EventName, data.Data);	//发给自己
		});
		socket.on('toOther', function(data) {
			socket.broadcast.emit(data.EventName, data.Data);		//发送除开自己的其他所有人
		});
		socket.on('toAll', function(data) {
			socketIo.emit(data.EventName, data.Data);	//发给所有人，包括自己
		});

		socket.on('joinRoom', function(data) {
			socket.join(data.RoomName);
		});
		socket.on('leaveRoom', function(data) {
			socket.leave(data.RoomName);
		});
		socket.on('toRoom', function(data) {
			socket.broadcast.to(data.RoomName).emit(data.EventName, data.Data);			//向一个房间广播消息（发送者收不到消息)
		});
		socket.on('inRoom', function(data) {
			socketIo.in(data.RoomName).emit(data.EventName, data.Data);		//向一个房间广播消息（包括发送者都能收到消息)
		});

		socket.on('disconnect', function () {
			console.log('disconnect');
			// socketIo.emit('logout', socket.name + ':用户退出');
			if(clientList.hasOwnProperty(socket.id)){
				socket.disconnect();
				delete clientList[socket.id];
			}
		});
		//程序调用，主动断开
		socket.on('clientDisconnect', function () {
			console.log('clientDisconnect');
			socket.ondisconnect();
		});

		socket.on('error', function (err) {
			if (err) {
	            try {
	            	BaseFun.errorLog("Scoket错误", "Socket异常关闭");
	            } catch (err) {
	            	console.log(err);
	            }

	            if(clientList.hasOwnProperty(socket.id)){
					delete clientList[socket.id];
				}
	        }
		});
	});

	console.log("即时通信服务开启，端口号：" + socketPort);
};

if(BaseConst.SocketPort){
	createServer(BaseConst.SocketPort);
}